/*
 * =====================================================================================
 *
 *       Filename:  Queue.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  11/09/2012 07:40:21 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Kjeldahl (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include "Queue.h"


Queue *initQueue(){
	elmType *data=malloc(sizeof(elmType)*SIZE);
	Queue *Q=malloc(sizeof(Queue));
	Q->data=data;
	Q->length=0;
	Q->rear=Q->front=-1;
	Q->MaxSize=SIZE;
	printf("init%x\n",Q->data);
	return Q;
}
void resizeQueue(Queue *Q,int size){
	//Unimplement......
	setMaxSize(Q,size);
	Q->data=realloc(Q->data,sizeof(elmType)*getMaxSize(Q));
}

void emptyQueue(Queue *Q){
	memset(Q->data,0,getMaxSize(Q));//resize vs SIZE
	Q->length=0;
	Q->rear=Q->front=-1;
}
void destroyQueue(Queue *Q){
	free(Q->data);
	free(Q);
}
void unshift(Queue *Q,elmType value){

	if((Q->rear+1)%getMaxSize(Q)==Q->front){
			resizeQueue(Q,SIZE);
			if(Q->rear < Q->front){
				memcpy(Q->data+Q->front+SIZE,Q->data+Q->front,sizeof(elmType)*(getMaxSize(Q)-SIZE-Q->front));
				Q->front=SIZE+Q->front;
				printf("hi%d\n",Q->front);

		}	
			Q->length++;
			Q->rear++;
			Q->data[Q->rear]=value;

	}else{
		Q->rear=((Q->rear+1)%getMaxSize(Q));
		Q->data[Q->rear]=value;
		Q->length++;
		if(Q->front==-1)
			Q->front=0;
	}

}
elmType pop(Queue *Q){
	if(isempty(Q)){
		printf("The Queue is empty\n");
		return -1;
	}else if(getLength(Q)==1){
		Q->rear=Q->front=-1;
		Q->length=0;
		printf("Now the Queue is empty\n");
		return Q->data[Q->front];
	}else{
		Q->front=(Q->front+1)%getMaxSize(Q);
		Q->length--;
		return Q->data[Q->front];
	}
}

int getLength(Queue *Q){

	return Q->length;

}
elmType getFront(Queue *Q){
	return Q->data[Q->front];

}
elmType getRear(Queue *Q){
	return Q->data[Q->rear];
}
void showQueue(Queue *Q){	
	int i=Q->length;
	int j=Q->front;
	printf("Front<-");
	for(;i!=0;i--){
		printf("%d<-",Q->data[j]);
		j=(j+1)%getMaxSize(Q);
	
	}
	printf("Rear\n");
}
int getMaxSize(Queue *Q){

	 return Q->MaxSize;

}
void  setMaxSize(Queue *Q,int size){

	Q->MaxSize+=size;
}
bool isempty(Queue *Q){
	if(Q->front==Q->rear && Q->front ==-1){
		return true;

	}else{
		return false;
	}
	/*
	 if(getLength(Q)==0){
         	return true;
	 }else{
        	 return false;
	 
	 }
	  */
}
